// 简化后的 request.js
import axios from 'axios'
import Vue from 'vue';
import router from '@/router'
const service = axios.create({
    baseURL: 'http://localhost:5080',
    timeout: 10000
});

// 请求拦截器：添加token到请求头
service.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token');
        if (token && !['/login', '/register'].includes(config.url)) {
            config.headers['token'] = token;
        }
        return config;
    },
    error => {
        console.error('请求拦截器错误:', error);
        return Promise.reject(error);
    }
);

// 响应拦截器：处理认证和权限错误
service.interceptors.response.use(
    response => response,
    error => {
        const { response } = error;

        // 使用全局 Vue 实例访问 $message
        const showMessage = (message) => {
            Vue.prototype.$message.error(message);
        };
        if (response.config.responseType === 'blob') {
            return response;
        }
        if (response && response.status === 401) {
            showMessage('登录状态已过期，请重新登录');

            // 清除本地存储的认证信息
            localStorage.removeItem('token');
            localStorage.removeItem('staff');
            localStorage.removeItem('userData');

            // 重置 Vuex 状态
            if (Vue.prototype.$store) {
                Vue.prototype.$store.commit('resetAuthState');
            }

            // 跳转到登录页
            router.push('/login');
        } else if (response && response.status === 403) {
            showMessage('权限不足，无法访问该资源');
        } else {
            showMessage(error.message || '请求失败');
        }

        return Promise.reject(error);
    }
);


export default service;